<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <p>{{ $t('上传Excel固定模板') }}</p>
          <el-button type="primary" @click="uploadHandle('excel')"> {{ $t('上传(Excel)') }}</el-button>
        </el-col>
        <el-col :span="12">
          <p>{{ $t('OCR识别') }}</p>
          <el-button type="primary" @click="uploadHandle('ocr')">{{ $t('上传(PDF,Excel,图片)') }}</el-button>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer" style="text-align: right;margin-top: 20px;">
        <!--保存，保存并启动流程，取消 三个按钮-->
        <SaveBtn has-permi="company:pcw" :save-btn-name="$t('确定')" :save-show="!outside || !!(outside && companyId && templateId)" />
      </div>

      <el-dialog
        :title="upload.title"
        :visible.sync="upload.open"
        width="400px"
        :close-on-click-modal="false"
        :lock-scroll="false"
        append-to-body
      >
        <div v-loading="upload.loading">
          <el-upload
            ref="upload"
            class="upload-demo"
            drag
            :http-request="uploadType !== 'ocr' ? undefined : httpRequest"
            :headers="upload.headers"
            :action="upload.url"
            :show-file-list="true"
            :disabled="upload.loading"
            :multiple="false"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :on-exceed="handleFileExceed"
            :on-change="onChange"
            :on-remove="onRemove"
            :auto-upload="false"
            :file-list="upload.fileList"
            :limit="upload.limit"
            :accept="upload.accept"
            :data="{ 'startPage': (upload.startPage ? upload.startPage : '0'), 'endPage': upload.endPage ? upload.endPage : '0' }"
            style="color: #1890ff;"
          >
            <i class="el-icon-upload" />
            <div class="el-upload__text">
              {{ $t('将文件拖到此处，或') }}
              <em>{{ $t('上传') }}</em>
            </div>
            <div slot="tip" class="el-upload__tip" style="color:red">
              {{ $t(upload.tip) }}
              <el-link v-if="!upload.pageHidden" type="primary" style="font-size:12px" @click="fetchTemplate">
                {{ $t('下载模板') }}
              </el-link>
            </div>
          </el-upload>
          <el-form v-if="upload.pageHidden" ref="uploadForm" :model="upload" label-width="120px" class="dataForm">
            <el-row>
              <el-col :span="24">
                <el-form-item prop="startPage" :rules="[{ required: true, message: $t('起始页不能为空'), trigger: 'blur' }]">
                  <span slot="label">
                    {{ $t('PDF起始页') }}
                    <el-tooltip placement="top">
                      <div slot="content">
                        <span v-html="$t('识别起始页和结束页区间的PDF页面；<br>')" />
                        <span v-html="$t('1.不输入全部识别；<br>')" />
                        <span v-html="$t('2.只输入起始页, 从起始页开始识别至文档末；<br>')" />
                        <span v-html="$t('3.只输入结束页, 从第一页开始识别至结束页；<br>')" />
                      </div>
                      <i class="el-icon-question" style="margin-top: 10px; margin-right: 10px;" />
                    </el-tooltip>
                  </span>
                  <el-input-number v-model="upload.startPage" :min="1" :max="999" :placeholder="$t('从N页开始')" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item :label="$t('PDF结束页')" prop="endPage" :rules="[{ required: true, validator: checkPage, trigger: 'blur' }]">
                  <el-input-number v-model="upload.endPage" :min="1" :max="999" :placeholder="$t('N页结束')" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer" style="text-align: right;">
            <el-button size="small" @click="upload.open = false">{{ $t('取消') }}</el-button>
            <el-button size="small" type="primary" @click="submitFileForm">{{ $t('上传') }}</el-button>
          </div>
        </div>
      </el-dialog>
      <!-- 财报识别 -->
      <el-dialog
        :title="$t('财报识别结果')"
        :visible.sync="ocrFormOpen"
        :close-on-click-modal="false"
        :lock-scroll="false"
        custom-class="dialogForm"
        append-to-body
      >
        <pcwOcrResult ref="pcwOcrResult" />
      </el-dialog>
    </el-form></div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { config } from '@/utils'
import { uploadSubject } from '@/api/company/pcw/pcwDataMain'

import { getConfigKey } from '@/api/system/config'
import { listCompanyBase } from '@/api/company/base/companyBase'
import pcwOcrResult from './pcwOcrResult.vue'

export default {
  name: 'PcwDataSubjectUpload',
  components: { pcwOcrResult },
  props: {
    outside: {
      type: Boolean,
      default: false,
      desc: '是否外部调用'
    },
    companyId: {
      type: String,
      default: undefined
    },
    typeId: {
      type: String,
      default: undefined
    },
    isSysTemp: {
       type: Boolean,
       default: true
    }
  },
  data() {
    return {
      form: {
        year: '',
        type: undefined,
        dataSource: 'act',
        currency: 'CNY'
      },
      upload: {
        open: false,
        loading: false,
        fileList: [],
        // 弹出层标题（项目导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: '',
        startPage: undefined,
        endPage: undefined,
        pageHidden: true,
        accept: '.xls, .xlsx',
        tip: '',
        multiple: false,
        limit: 5
      },
      open: false,
      base64: '',
      responseData: {},
      queryParams: {
      },
      loading: false,
      typeOptions: [],
      sysPcwTypeOptions: [],
      templateId: undefined,
      companyOptions: [],
      dataSourceOptions: [],
      uploadType: '',
      formData: '',
      ocrFormOpen: false
    }
  },
  created() {
  },
  methods: {
    init() {
      if (this.outside) {
        this.templateId = undefined
        this.sysPcwTypeOptions = []
        listCompanyBase({}).then(response => {
          this.companyOptions = response.rows
        })
      }
      delete this.form.sheetData
      this.responseData = {}
      this.upload.fileList = []
      this.upload.startPage = undefined
      this.upload.endPage = undefined
      this.loading = false
      this.$refs.form.resetFields()
    },
    // 文件上传中处理
    handleFileUploadProgress() {
      this.upload.loading = true
    },
    // 文件上传成功处理
    handleFileSuccess(resp) {
      this.upload.open = false
      this.upload.loading = false
      this.$refs.upload.clearFiles()
      if (resp.code === 200 && resp.data === 'excel') {
          this.upload.open = false
          this.$parent.$parent.uploadFormOpen = false
          this.$parent.$parent.getList()
      } else if (resp.code === 200 && resp.data === 'ocr') {
         // 判断是否有匹配科目
        this.openPcwOcr(resp)
      } else {
        this.msgError(resp.msg)
      }
      // fileList.splice(fileList.length - 1, 1)
      // this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
    },
     // 财务识别完成之后打开财务识别弹窗
    openPcwOcr(resp) {
      this.ocrFormOpen = true
      this.$nextTick(() => {
        this.$refs.pcwOcrResult.form.pdList = resp.datas.pdList
        this.$refs.pcwOcrResult.form.cfList = resp.datas.cfList
        this.$refs.pcwOcrResult.form.bsList = resp.datas.bsList
        this.$refs.pcwOcrResult.source = 'temp'
      })
    },
    // 提交上传文件
    submitFileForm() {
      let flag = true
      if (this.$refs.upload.uploadFiles.length === 0) {
        this.msgWarning(this.$t('请至少上传一个文件'))
        return false
      }
      if (this.upload.pageHidden) {
        this.$refs.uploadForm.validate(valid => {
          if (valid) {
            if (this.uploadType === 'ocr') {
              this.formData = new FormData()
            }
            this.$refs.upload.submit()
          } else {
            flag = false
            return false
          }
        })
      } else {
        if (this.uploadType === 'ocr') {
          this.formData = new FormData()
        }
        this.$refs.upload.submit()
      }
      if (!flag) {
        return false
      }
      if (this.uploadType === 'ocr') {
        this.upload.loading = true
        if (this.upload.startPage && this.upload.endPage) {
          this.formData.append('startPage', this.upload.startPage)
          this.formData.append('endPage', this.upload.endPage)
        }
        uploadSubject(this.formData).then(res => {
          this.handleFileSuccess(res)
        })
      }
    },
    onChange(file, fileList) {
      if (file.raw.type.indexOf('image') !== -1 || file.name.indexOf('xlsx') !== -1 || file.name.indexOf('xls') !== -1 || fileList.length > 1) {
        this.upload.pageHidden = false
      } else {
        this.upload.pageHidden = true
      }
    },
    // 文件达到上限处理
    handleFileExceed() {
      this.msgError(this.$t('最多可上传' + this.upload.limit + '个文件'))
      // this.msgError(this.$t('最多可上传{limit}个文件', { limit: this.upload.limit }))
    },
    checkPage(rule, value, callback) {
      if (!this.upload.endPage) {
        callback(this.$t('结束页不能为空'))
      } else {
        if (this.upload.startPage > this.upload.endPage) {
          callback(new Error(this.$t('结束页不能大于起始页')))
        }
        callback()
      }
    },
    uploadHandle(type) {
      this.upload.fileList = []
      if (type === 'excel') {
        this.uploadType = 'excel'
        this.upload.title = this.$t('Excel上传')
        this.upload.pageHidden = false
        this.upload.accept = '.xls, .xlsx'
        this.upload.tip = '提示：仅支持Excel文件'
        this.upload.limit = 1
        this.upload.multiple = false
        this.upload.url = config.baseURL + '/pcw/pcwDataMain/uploadSubjectToExcel?typeId=' + this.typeId + '&isSysTemp=' + this.isSysTemp + '&companyId=' + this.companyId
      } else {
        this.uploadType = 'ocr'
        this.upload.title = this.$t('OCR上传')
        this.upload.pageHidden = true
        this.upload.accept = '.xls, .xlsx, .pdf, image/*'
        this.upload.tip = '提示：支持图片、PDF、Excel文件'
        this.upload.limit = 5
        this.upload.multiple = false
        this.upload.url = config.baseURL + '/pcw/pcwDataMain/uploadSubject'
        this.upload.startPage = undefined
        this.upload.endPage = undefined
      }
       this.upload.open = true
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 下载模板
    fetchTemplate() {
      var href1 = window.location.href
      var href2 = this.$route.path
      var url = href1.substring(0, href1.indexOf(href2))
      getConfigKey('download_default_template').then(res => {
        debugger
        if (res.msg === 'true') {
          this.downLoadExcel('/pcw/pcwTempSubject/export/', { companyId: this.$route.query.companyId })
        } else {
          window.location.href = url + '/template/' + res.msg
        }
      })
    },
    httpRequest(file) {
      this.formData.append('file', file.file)
    },
    onRemove(file, fileList) {
      if (this.uploadType === 'ocr' && (fileList.length === 0) || (fileList.length === 1 && fileList[0].name.indexOf('pdf') !== -1)) {
        this.upload.pageHidden = true
      }
    }
  }
}
</script>

<style scoped>
.upload-demo /deep/ .el-upload-list {
  height: auto;
}
</style>
